<template>
  <div class="storagelocation-page">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" label-width="100px">
        <el-form-item label="库区名称">
          <el-input
            v-model="searchForm.storagelocationName"
            placeholder="请输入库区名称"
            clearable
            style="width: 260px"
          />
        </el-form-item>
        <el-form-item label="选择仓库">
          <el-select
            v-model="searchForm.warehouseId"
            placeholder="请选择"
            filterable
            clearable
            style="width: 260px"
            :loading="warehouseLoading"
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="table-card">
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="openDialog">添加</el-button>
        <el-button type="danger" :disabled="multipleSelection.length === 0" @click="handleBatchDelete">
          删除
        </el-button>
      </div>
      <el-table
        :data="tableData"
        row-key="storagelocationId"
        style="width: 100%"
        v-loading="loading"
        height="350px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" fixed="left" />
        <el-table-column fixed="left" type="index" label="序号" width="60" />
        <el-table-column prop="storagelocationName" label="库区名称" width="150" />
        <el-table-column prop="storagelocationCode" label="库区编码" width="120" />
        <el-table-column prop="warehouseName" label="所属库房" width="200" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.storagelocationState === 1 ? 'success' : 'danger'">
              {{ row.storagelocationState === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="storagelocationCapacity" label="库区面积" width="120" />
        <el-table-column label="操作时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime || row.createrTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作人" width="120">
          <template #default="{ row }">
            {{ row.updater || row.createor || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280">
          <template #default="{ row }">
            <el-button link size="small" type="primary" @click="openEditDialog(row)">编辑</el-button>
            <el-button link size="small" type="info" @click="openDetailDialog(row)">查看</el-button>
            <el-button link size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <el-card class="action-card">
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pageinfo.pageIndex"
          v-model:page-size="pageinfo.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="pageinfo.total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑库区弹框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogMode === 'add' ? '新增' : '编辑'" 
      width="700px" 
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库位编号" prop="storagelocationCode">
              <el-input 
                v-model="form.storagelocationCode" 
                :placeholder="dialogMode === 'add' ? '请点击自动生成按钮获取编号' : '库位编号'" 
                readonly
              >
                <template #append v-if="dialogMode === 'add'">
                  <el-button @click="generateStoragelocationCode" :loading="generatingCode">自动生成</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位名称" prop="storagelocationName">
              <el-input 
                v-model="form.storagelocationName" 
                placeholder="请输入库位名称" 
                clearable 
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择仓库" prop="warehouseId">
              <el-select
                v-model="form.warehouseId"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :loading="warehouseLoading"
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位容量/m³" prop="storagelocationCapacity">
              <el-input 
                v-model="form.storagelocationCapacity" 
                placeholder="请输入库位容量" 
                clearable 
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="storagelocationSort">
              <el-input-number 
                v-model="form.storagelocationSort" 
                :min="0" 
                :controls="false" 
                style="width: 100%" 
                placeholder="请输入排序"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库主管" prop="userId">
              <el-select
                v-model="form.userId"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :loading="userLoading"
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库位状态" prop="storagelocationState">
              <el-radio-group v-model="form.storagelocationState">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="2">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="form.storagelocationNote"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSave" 
            :loading="saving"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import myaxios from '@/http/MyAxios'

// 查询条件
const searchForm = reactive({
  storagelocationName: '', // 库区名称（模糊查询）
  warehouseId: null as number | null, // 所属仓库（精确查询）
})

// 分页信息
const pageinfo = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

// 列表数据
const tableData = ref<any[]>([])
const loading = ref(false)
const multipleSelection = ref<any[]>([])

// 仓库选项（使用站台页面的数据源）
const warehouseOptions = ref<Array<{ warehouseId: number; warehouseName: string }>>([])
const warehouseLoading = ref(false)

// 弹框相关
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add') // 弹框模式：add-新增，edit-编辑
const currentEditId = ref<number | null>(null) // 当前编辑的库区ID
const formRef = ref<FormInstance>()
const saving = ref(false)

// 用户选项（仓库主管）
const userOptions = ref<Array<{ userId: number; userName: string }>>([])
const userLoading = ref(false)

// 编号生成相关
const generatingCode = ref(false)

// 表单数据
const form = reactive({
  storagelocationId: null as number | null,
  storagelocationName: '',
  storagelocationCode: '',
  storagelocationCapacity: '',
  storagelocationSort: 0,
  userId: null as number | null,
  storagelocationState: 1, // 默认启用
  storagelocationNote: '',
  warehouseId: null as number | null, // 需要选择仓库
})

// 表单验证规则
const rules: FormRules = {
  storagelocationName: [{ required: true, message: '请输入库位名称', trigger: 'blur' }],
  storagelocationCode: [{ required: true, message: '请生成库位编号', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  storagelocationSort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  userId: [{ required: true, message: '请选择仓库主管', trigger: 'change' }],
  storagelocationState: [{ required: true, message: '请选择库位状态', trigger: 'change' }],
}

const formatDate = (val?: string | Date | null) => {
  if (!val) return '-'
  return dayjs(val).format('YYYY-MM-DD')
}

// 加载仓库列表（复用站台页面的逻辑）
const loadWarehouses = async () => {
  if (warehouseLoading.value) return
  warehouseLoading.value = true
  try {
    const res = await myaxios({
      url: '/api/Warehousing/GetWarehouse',
      method: 'get',
    })
    if (res.data?.code === 200 || res.data?.success) {
      const warehouses = res.data.data || []
      warehouseOptions.value = warehouses.map((item: any) => ({
        warehouseId: item.warehouseId,
        warehouseName: item.warehouseName,
      }))
    } else {
      ElMessage.error(res.data?.message || '获取仓库列表失败')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败，请稍后重试')
  } finally {
    warehouseLoading.value = false
  }
}

// 获取库区列表（分页）
const getStoragelocationList = () => {
  loading.value = true
  myaxios({
    url: '/api/Warehouse/GetStoragelocationPage',
    method: 'get',
    params: {
      Pageindex: pageinfo.pageIndex,
      PageSize: pageinfo.pageSize,
      storagelocationName: searchForm.storagelocationName || undefined,
      warehouseId: searchForm.warehouseId || undefined,
    },
  })
    .then(res => {
      const data = res.data?.data
      // 后端分页结构：data.data 为列表，data.listCount 为总数
      tableData.value = data?.data || []
      pageinfo.total = data?.listCount || 0
    })
    .catch(err => {
      console.error('获取库区列表失败:', err)
      ElMessage.error('获取库区列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 查询
const handleSearch = () => {
  pageinfo.pageIndex = 1
  getStoragelocationList()
}

// 重置
const handleReset = () => {
  searchForm.storagelocationName = ''
  searchForm.warehouseId = null
  pageinfo.pageIndex = 1
  // 重置后重新加载全部数据
  getStoragelocationList()
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

// 分页尺寸变化
const handleSizeChange = (val: number) => {
  pageinfo.pageSize = val
  pageinfo.pageIndex = 1
  getStoragelocationList()
}

// 页码变化
const handleCurrentChange = (val: number) => {
  pageinfo.pageIndex = val
  getStoragelocationList()
}

// 加载用户列表（仓库主管）
const loadUsers = async () => {
  if (userLoading.value) return
  userLoading.value = true
  try {
    const res = await myaxios({
      url: '/api/Warehouse/GetUser',
      method: 'get',
    })
    if (res.data?.code === 200 || res.data?.success) {
      const users = res.data.data || []
      userOptions.value = users.map((item: any) => ({
        userId: item.userId,
        userName: item.userName,
      }))
    } else {
      ElMessage.error(res.data?.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败，请稍后重试')
  } finally {
    userLoading.value = false
  }
}

// 编号生成相关函数
const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const indexA = TIME_SEGMENT_ORDER.indexOf(a)
      const indexB = TIME_SEGMENT_ORDER.indexOf(b)
      if (indexA === -1 && indexB === -1) return 0
      if (indexA === -1) return 1
      if (indexB === -1) return -1
      return indexA - indexB
    })
  const datePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const seq = '1'.padStart(rule?.serialLength || 3, '0')
  return `${rule?.codePrefix || ''}${datePart}${seq}`
}

const requestStoragelocationCode = async () => {
  try {
    // 直接调用 QueryNumberingRules 接口获取编号规则
    // 尝试多个可能的 targetName 值
    const possibleNames = ['库位', '库区', 'Storagelocation']
    let list: any[] = []
    
    for (const targetName of possibleNames) {
      try {
        const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
          params: { targetCode: 'Storagelocation', targetName }
        })
        
        // 检查响应码
        if (ruleRes?.data?.code !== 200 && ruleRes?.data?.code !== undefined) {
          console.warn(`[storagelocation] 接口返回异常 (${targetName}):`, ruleRes.data)
          continue
        }
        
        const data = ruleRes?.data?.data
        if (Array.isArray(data) && data.length > 0) {
          list = data
          console.log(`[storagelocation] 找到编号规则 (${targetName}):`, data[0])
          break
        }
      } catch (err) {
        console.warn(`[storagelocation] 尝试 ${targetName} 失败:`, err)
        continue
      }
    }
    
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    
    // 如果都失败，尝试只使用 targetName 参数
    try {
      const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
        params: { targetName: '库位' }
      })
      const data = ruleRes?.data?.data
      if (Array.isArray(data) && data.length > 0) {
        return buildCodeFromRule(data[0])
      }
    } catch (err) {
      console.warn('[storagelocation] 仅使用 targetName 参数也失败:', err)
    }
    
    throw new Error('未找到对应的编号规则，请先配置编号规则（targetName: 库位/库区）')
  } catch (err: any) {
    console.error('[storagelocation] 获取编号规则失败', err)
    throw new Error(err?.message || '获取编号规则失败，请先配置编号规则')
  }
}

const generateStoragelocationCode = async () => {
  generatingCode.value = true
  try {
    form.storagelocationCode = await requestStoragelocationCode()
    ElMessage.success('编号生成成功')
  } catch (err: any) {
    ElMessage.error(err?.message || '生成编号失败')
  } finally {
    generatingCode.value = false
  }
}

// 重置表单
const resetForm = () => {
  form.storagelocationId = null
  form.storagelocationName = ''
  form.storagelocationCode = ''
  form.storagelocationCapacity = ''
  form.storagelocationSort = 0
  form.userId = null
  form.storagelocationState = 1
  form.storagelocationNote = ''
  form.warehouseId = null
  currentEditId.value = null
  formRef.value?.clearValidate()
}

// 打开新增弹框
const openDialog = () => {
  dialogMode.value = 'add'
  resetForm()
  loadWarehouses()
  loadUsers()
  dialogVisible.value = true
  // 默认输入框为空，用户点击"自动生成"按钮时再生成编号
}

// 保存库区
const handleSave = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  // 新增模式下，如果用户没有输入库区编码，自动生成
  if (dialogMode.value === 'add' && !form.storagelocationCode) {
    try {
      await generateStoragelocationCode()
      // 如果生成失败，停止保存
      if (!form.storagelocationCode) {
        ElMessage.warning('请先生成库区编码')
        return
      }
    } catch (error) {
      ElMessage.warning('生成库区编码失败，请稍后重试')
      return
    }
  }

  saving.value = true
  try {
    const data = {
      storagelocationName: form.storagelocationName,
      storagelocationCode: form.storagelocationCode,
      storagelocationCapacity: form.storagelocationCapacity || '',
      storagelocationSort: form.storagelocationSort,
      userId: form.userId,
      storagelocationState: form.storagelocationState,
      storagelocationNote: form.storagelocationNote || '',
      warehouseId: form.warehouseId,
    }

    let res
    if (dialogMode.value === 'add') {
      // 新增
      res = await myaxios({
        url: '/api/Warehouse/CreateStoragelocation',
        method: 'post',
        data,
      })
    } else {
      // 编辑
      if (!currentEditId.value) {
        ElMessage.error('缺少库区ID')
        return
      }
      res = await myaxios({
        url: `/api/Warehouse/UpdateStoragelocation?storagelocationId=${currentEditId.value}`,
        method: 'put',
        data,
      })
    }

    if (res.data?.code === 200) {
      ElMessage.success(res.data?.message || (dialogMode.value === 'add' ? '添加库区成功' : '更新库区成功'))
      dialogVisible.value = false
      getStoragelocationList()
    } else {
      ElMessage.error(res.data?.message || (dialogMode.value === 'add' ? '添加库区失败' : '更新库区失败'))
    }
  } catch (error: any) {
    console.error(`${dialogMode.value === 'add' ? '添加' : '更新'}库区失败:`, error)
    const errorMsg =
      error?.response?.data?.message ||
      error?.message ||
      `${dialogMode.value === 'add' ? '添加' : '更新'}库区失败，请稍后重试`
    ElMessage.error(errorMsg)
  } finally {
    saving.value = false
  }
}

// 打开编辑弹框
const openEditDialog = (row: any) => {
  dialogMode.value = 'edit'
  resetForm()
  loadWarehouses()
  loadUsers()
  
  // 填充表单数据
  currentEditId.value = row.storagelocationId
  form.storagelocationId = row.storagelocationId
  form.storagelocationName = row.storagelocationName || ''
  form.storagelocationCode = row.storagelocationCode || ''
  form.storagelocationCapacity = row.storagelocationCapacity || ''
  form.storagelocationSort = row.storagelocationSort || 0
  form.userId = row.userId || null
  form.storagelocationState = row.storagelocationState ?? 1
  form.storagelocationNote = row.storagelocationNote || ''
  form.warehouseId = row.warehouseId || null
  
  dialogVisible.value = true
}

// 打开详情弹框（占位函数，后续可扩展）
const openDetailDialog = (row: any) => {
  ElMessage.info('查看功能待实现')
}

// 单个删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    '确认删除这条库区信息吗？',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      myaxios({
        url: '/api/Warehouse/AllDeleteStoragelocation',
        method: 'delete',
        params: { storagelocationIds: String(row.storagelocationId) },
      })
        .then(res => {
          if (res.data?.code === 200) {
            ElMessage.success(res.data?.message || '删除成功')
            getStoragelocationList()
          } else {
            ElMessage.error(res.data?.message || '删除失败')
          }
        })
        .catch(error => {
          console.error('删除库区失败:', error)
          ElMessage.error('删除库区失败，请稍后重试')
        })
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的库区')
    return
  }

  ElMessageBox.confirm(
    `确认删除选中的 ${multipleSelection.value.length} 条库区信息吗？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const ids = multipleSelection.value.map(item => item.storagelocationId)
      const idsString = ids.join(',')
      
      myaxios({
        url: '/api/Warehouse/AllDeleteStoragelocation',
        method: 'delete',
        params: { storagelocationIds: idsString },
      })
        .then(res => {
          if (res.data?.code === 200) {
            ElMessage.success(res.data?.message || '批量删除成功')
            multipleSelection.value = []
            getStoragelocationList()
          } else {
            ElMessage.error(res.data?.message || '批量删除失败')
          }
        })
        .catch(error => {
          console.error('批量删除库区失败:', error)
          ElMessage.error('批量删除库区失败，请稍后重试')
        })
    })
    .catch(() => {
      // 用户取消删除
    })
}

onMounted(() => {
  loadWarehouses()
  // 页面初始化时加载全部库区数据
  getStoragelocationList()
})
</script>

<style scoped>
.storagelocation-page {
  padding: 10px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 15px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>

